import React, { Component } from 'react'
import pubSub from "pubsub-js";
import axios from "axios";

export default class Row extends Component {
    state = {
        items: [],
        isStart: false,
        isLoading: false

    }
    render() {
        if (!this.state.isStart) {
            return <h3>请输入搜索的关键词，点击搜索按钮进行搜索</h3>
        }
        if (this.state.isLoading) {
            return <h3>正在拼命加载中……</h3>
        }
        if (this.state.items.length === 0) {
            return <h3>未搜索到您要的结果</h3>
        }

        return (
            <div className="row">
                {
                    this.state.items.map(item => (
                        <div className="card" key={item.id}>
                            <a href={item.html_url} target="_blank">
                                <img src={item.avatar_url} style={{ width: 100 }} />
                            </a>
                            <p className="card-text">{item.login}</p>
                        </div>
                    ))
                }
            </div>
        )
    }



    getData() {
        pubSub.subscribe('search', async (msgName, keyword) => {
            axios.interceptors.response.use((res) => {
                return res
            })

            this.setState({
                isStart: true,
                isLoading: true
            })
            const {data: {items}} = await axios.get('https://api.github.com/search/users', {
                params: {
                    q: keyword,
                    sort: 'start'
                }
            })
            this.setState({
                items,
                isLoading: false,
            })
        })
    }
    componentDidMount() {
        this.getData()
    }
    componentWillUnmount() {
        // 移除订阅者
        pubSub.unsubscribe('search')
    }
}
